package cn.fulong.sso.client.listener;

import cn.fulong.sso.client.manager.SessionManager;
import cn.fulong.sso.client.utils.SessionManagerUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;


/**
 * @desc:
 * @author: 云树
 * @createDate: 2019/1/16 21:15
 * @version: 1.0
 */
@Slf4j
public class SessionListener implements HttpSessionListener {

    private volatile SessionManager sessionManager;

    private Object lock = new Object();

    public SessionListener() {
        log.debug("SessionListener created");
    }

    @Override
    public void sessionCreated(HttpSessionEvent se) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent arg0) {
        HttpSession session = arg0.getSession();
        log.debug("【session destroyed】start");
        getSessionManager(session).removeSessionManagerBySession(session);
        log.debug("【session destroyed】清除客户端会话");
    }

    /**
     * @param session
     * @return 最好系统启动完先登录测试预热系统
     */
    private SessionManager getSessionManager(HttpSession session) {
        if (this.sessionManager == null) {
            synchronized (lock) {
                if (this.sessionManager == null) {
                    ServletContext servletContext = session.getServletContext();
                    //获取SSo服务端全局配置
                    this.sessionManager = SessionManagerUtils.getRegisterSessionMangerBean(servletContext);
                }
            }
        }
        return this.sessionManager;
    }
}
